﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iLangl.Utils;
using System.Data;

namespace iLangl.LanguageWire.DAL.iLanglDAL.XMLStorage
{
	public class XMLStorageManager : BaseMockupStorageManager
	{
		private XMLStorageManager(string filename) : base(filename)
		{
		}

		private static XMLStorageManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the XmlStorageManager.
		/// </summary>
		public static XMLStorageManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new XMLStorageManager(XMLStorageConfigurationILangl.Instance.FilePathToStorage);
						}
					}
				}
				return instance;
			}
		}

		private dtoXMLStorage _storage = null;
		public dtoXMLStorage Storage
		{
			get
			{
				if (_storage == null)
				{
					_storage = new dtoXMLStorage();

					if (!File.Exists(StorageFileName))
					{
						Save();
					}

					read();
				}

				return _storage;
			}
		}

		protected override void readStorage()
		{
			_storage = new dtoXMLStorage();

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.BeginLoadData();

			try
			{
				_storage.ReadXml(StorageFileName);
			}
			catch
			{
			}

			foreach (DataTable dataTable in _storage.Tables)
				dataTable.EndLoadData();

			
		}

		public void AcceptChanges()
		{
			Storage.AcceptChanges();
			Save();
		}

		
		protected override void saveStorage()
		{
			
			Storage.WriteXml(StorageFileName);
			
		}
	}
}